package com.zhyz.bookstore.servlet;

import com.zhyz.bookstore.entity.*;
import com.zhyz.bookstore.service.ClientService;
import com.zhyz.bookstore.service.ManagerService;
import com.zhyz.bookstore.service.impl.ClientServiceImpl;
import com.zhyz.bookstore.service.impl.ManagerServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * 客户端servlet
 */
@WebServlet(name = "ClientServlet ", value = "/client/ClientServlet")
public class ClientServlet extends HttpServlet {

    private ClientService clientService = new ClientServiceImpl();
    private ManagerService managerService = new ManagerServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 得到传过来的请求
        String op = request.getParameter("op");
        if (op != null && !op.equals("")) {
            switch (op) {
                //用户登录
                case "login":
                    login(request, response);
                    break;
                //用户退出登录
                case "layout":
                    layout(request, response);
                    break;
                //用户注册
                case "register":
                    register(request, response);
                    break;
                //书籍列表
                case "category":
                    getCategoryBook(request, response);
                    break;
                case "search":
                    selSearchBook(request, response);
                    break;
                case "particulars":
                    particulars(request, response);
                    break;
                // 添加收藏夹
                case "addfavorite":
                    addfavorite(request, response);
                    break;
                // 显示收藏夹
                case "showfavorite":
                    showfavorite(request, response);
                    break;
                // 删除收藏夹
                case "delFavorite":
                    delFavorite(request, response);
                    break;
                // 删除收藏夹
                case "buyNow":
                    buNow(request, response);
                    break;
                //小郑
                case "personInformation":
                    personInformation(request,response);
                    break;
                //小郑
                case "personPassword":
                    personPassword(request,response);
                    break;
            }
        }
    }

    private void buNow(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String book_id = request.getParameter("book_id");
        Book book = getBookByid(book_id);
        HttpSession session = request.getSession();
        Cart cart = new Cart();
        session.setAttribute("buyNowBook", cart);
        cart.addBook(book);
        response.sendRedirect(request.getContextPath() + "/buyNow.jsp");
    }

    private void delFavorite(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String book_id = request.getParameter("BookId");
        clientService.delFavorite(book_id);
        HttpSession session = request.getSession();
        List<Favorite> lists = (List<Favorite>) session.getAttribute("favorite");
        Iterator<Favorite> iterator = lists.iterator();
        while (iterator.hasNext()) {
            Favorite favorite = iterator.next();
            if (book_id.equals(favorite.getBook().getBookId())) {
                iterator.remove();// 使用迭代器的删除方法删除
            }
        }
        response.sendRedirect(request.getContextPath() + "/favorite.jsp");
    }

    private void showfavorite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        List<Favorite> favorites = clientService.findFavoriteByUserId(user);
        session.setAttribute("favorite", favorites);
        request.getRequestDispatcher("/favorite.jsp").forward(request, response);
    }

    private void addfavorite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String user_id = user.getId();
            String book_id = request.getParameter("BookId");
        System.out.println(book_id);
        boolean isExit = clientService.findFavorite(user_id, book_id);
        if (isExit == false) {
            clientService.addfavorite(user_id, book_id);
        }
        showfavorite(request,response);
    }

    //详情页面
    private void particulars(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String BookId = request.getParameter("book_id");
        Book book = getBookByid(BookId);
        request.setAttribute("book", book);
        request.getRequestDispatcher("/particulars.jsp").forward(request, response);

    }

    private Book getBookByid(String BookId) {
        Book book = managerService.getBooks(BookId);
        return book;
    }

    //搜索
    private void selSearchBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String seach = request.getParameter("search");
        List<Book> searchMessage = clientService.search(seach);
        request.setAttribute("books", searchMessage);
        request.getRequestDispatcher("/showBook.jsp").forward(request, response);
    }

    //书籍列表
    private void getCategoryBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cid = request.getParameter("cid");
        List<Book> books = clientService.getCategoryBook(cid);
        request.setAttribute("books", books);
        List<Category> categoryList = managerService.getAllCatrgory();
        request.setAttribute("categoryList", categoryList);
        request.getRequestDispatcher("/showBook.jsp").forward(request, response);
    }

    //用户注册
    private void register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String tel = request.getParameter("tel");
        String address = request.getParameter("address");
        // 判断是否存在该用户
        boolean isExist = false;
        if (!username.equals("") && !password.equals("")) {
            isExist = clientService.register(username, password, name, sex, tel, address);
            if (isExist == true) {
                response.getWriter().write("该用户已经注册，请直接");
                response.getWriter().write("<a href='\" + req.getContextPath() + \"/client/ClientServlet?op=category'>登录</a>");
            } else {
                response.getWriter().write("注册成功！");
                response.getWriter().write("2s后跳转到登录页面！");
                response.setHeader("Refresh","2;URL=" + request.getContextPath() + "/client/ClientServlet?op=category");
            }
        }
    }

    //用户退出登录
    private void layout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        // 获取session对象，从session中移除登陆信息
        session.removeAttribute("user");
        response.sendRedirect("/");

    }

    //用户登录
    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        HttpSession session = request.getSession();
        User user = clientService.login(username, password);
        if (user.getUsername() != null && user.getUsername() != "") {
            request.setAttribute("message", "登陆成功！");
            session.setAttribute("user", user);
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        } else {
            request.setAttribute("message", "用户名或密码错误，请重新登录");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        }
    }

    private void personInformation(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String tel = request.getParameter("tel");
        String address = request.getParameter("address");

        clientService.personInformation(username, name, sex, tel, address);
        response.getWriter().write("<div style='text-align: center;margin-top: 260px'><img src='" + request.getContextPath()
                + "/img/duigou.png'/>修改成功！</div>");
    }

    //修改管理员密码
    private void personPassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        clientService.personPassword(password, username);
        response.getWriter().write("<div style='text-align: center;margin-top: 260px'><img src='" + request.getContextPath()
                + "/img/duigou.png'/>修改成功！</div>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
